if (getCookie("songNumber") == "")
	setCookie("songNumber", -1, 1);

var songNumber = getCookie("songNumber");
songNumber++;
setCookie("songNumber", songNumber, 365);

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

document.getElementById('clientLink').innerHTML = '<h2>Edit playlist @ <a href="?tp=' + browserId + '" target="_blank">http://' + location.host + '?tp=' + browserId + '</a></h2>';

function onYouTubeIframeAPIReady() {
	player = new YT.Player('player', {
		width : '800',
		height : '400',
		videoId : '',
		playerVars : {
			'autoplay' : 1,
			'controls' : 0
		},
		events : {
			'onReady' : onPlayerReady,
			'onStateChange' : onPlayerStateChange
		}
	});
}

function onPlayerReady(event) {
	php('sync', 'Teamplayer/getPlaylistHtml', songNumber);
	var videoId = "";
	if (document.getElementById('firstVideo') != null)
		videoId = document.getElementById('firstVideo').value;
	if (videoId == "")
		videoId = initialVideoId;
	player.loadVideoById({
		'videoId' : videoId
	});
}

function onPlayerStateChange(event) {
	if (event.data == 0) {
		songNumber++;
		setCookie("songNumber", songNumber, 365);
		php('sync', 'Teamplayer/getPlaylistHtml', songNumber);
		var videoId = "";
		if (document.getElementById('firstVideo') != null)
			videoId = document.getElementById('firstVideo').value;
		if (videoId == "")
			videoId = initialVideoId;
		player.loadVideoById({
			'videoId' : videoId
		});
	}
}
